package com.ash.util;

import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @encoding : UTF-8
 * @Time : 2020/12/3 20:49
 * @Author : Chen Chao
 * @File : connection.com.ash.util.ConnectionUtil.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 数据库连接工具类
 */
public class ConnectionUtil {
    protected static String url;
    protected static String user;
    protected static String password;
    protected static String className;

    static {
        Properties properties = new Properties();
        try (FileReader fileReader = new FileReader
                ("src/com/ash/util/connection.properties")
        ) {
            /*加载配置*/
            properties.load(fileReader);
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            className = properties.getProperty("className");

            /*驱动只要加载一次，所以放在static代码块中*/
            Class.forName(className);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取数据库连接
     *
     * @return 返回数据库连接
     */
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }

    /**
     * 关闭数据库资源
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
